﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Text;
using System.Web.Script.Serialization;
using Newtonsoft.Json.Linq;
using BLL;
using WeChat.JsSDK.lib;
/*
 *客服账号设置
 *最多添加10个客服账号
 *客服账号设置规则默认是 账号@公众号 eg:test@sj_jocat
 */
namespace WeChat.Common
{
    public class SetKefu
    {
        GetReturnJson gt = new GetReturnJson();
        KefuBLL kf = new KefuBLL();
        //string accesstoken = GetAccess_token.getAccesstoken();
        /// <summary>
        /// 创建客服账号
        /// </summary>
        /// <param name="kefuAccount">客服账号</param>
        /// <param name="kefuName">客服昵称</param>
        /// <param name="password">客服密码</param>
        public string setNewKefu(string kefuAccount,string kefuName,string password)
        {
            string url = "https://api.weixin.qq.com/customservice/kfaccount/add?access_token=" + GetAccess_token.getAccesstoken();

            StringWriter sw = new StringWriter();
            JsonWriter writer = new JsonTextWriter(sw);//新建json存入客服信息
            writer.WriteStartObject();
            writer.WritePropertyName("kf_account");
            writer.WriteValue(kefuAccount);//设置客服账号
            writer.WritePropertyName("nickname");
            writer.WriteValue(kefuName);//设置客服昵称
            writer.WritePropertyName("password");
#pragma warning disable CS0618 // “FormsAuthentication.HashPasswordForStoringInConfigFile(string, string)”已过时:“The recommended alternative is to use the Membership APIs, such as Membership.CreateUser. For more information, see http://go.microsoft.com/fwlink/?LinkId=252463.”
            string pwd = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(password, "MD5").ToString();//设置客服密码
#pragma warning restore CS0618 // “FormsAuthentication.HashPasswordForStoringInConfigFile(string, string)”已过时:“The recommended alternative is to use the Membership APIs, such as Membership.CreateUser. For more information, see http://go.microsoft.com/fwlink/?LinkId=252463.”
            writer.WriteValue(pwd);
            writer.WriteEndObject();
            writer.Flush();
            string json = sw.GetStringBuilder().ToString();
            var js = new JavaScriptSerializer();
            var dic = js.Deserialize<Dictionary<string, object>>(gt.postReturnJson(url, json));
            //Dictionary<string, object> dic = GetReturnJson.CreatePostHttpResponse(url, json, null, null, Encoding.GetEncoding("utf-8"),null);


            if (dic["errcode"].ToString().Equals("0"))
            {
                //同步更新数据库
                kf.addKefu(kefuAccount, kefuName, password);
                ApplicationLog.Write("新增客服成功！");
                return "新增客服成功!";
            }
            else
            {
                ApplicationLog.Write("新增客服失败！errcode：" + dic["errcode"]);
                return "新增客服失败！errcode：" + dic["errcode"];
            }
        }
        /// <summary>
        /// 修改客服信息
        /// </summary>
        /// <param name="kefuAccount"></param>
        /// <param name="kefuName"></param>
        /// <param name="password"></param>
        public string updateKefu(string kefuAccount, string kefuName, string password)
        {
            string url = "https://api.weixin.qq.com/customservice/kfaccount/update?access_token=" + GetAccess_token.getAccesstoken();

            StringWriter sw = new StringWriter();
            JsonWriter writer = new JsonTextWriter(sw);//新建json存入客服信息
            writer.WriteStartObject();
            writer.WritePropertyName("kf_account");
            writer.WriteValue(kefuAccount);//设置客服账号
            writer.WritePropertyName("nickname");
            writer.WriteValue(kefuName);//设置客服昵称
            writer.WritePropertyName("password");
#pragma warning disable CS0618 // “FormsAuthentication.HashPasswordForStoringInConfigFile(string, string)”已过时:“The recommended alternative is to use the Membership APIs, such as Membership.CreateUser. For more information, see http://go.microsoft.com/fwlink/?LinkId=252463.”
            string pwd = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(password, "MD5").ToString();//设置客服密码
#pragma warning restore CS0618 // “FormsAuthentication.HashPasswordForStoringInConfigFile(string, string)”已过时:“The recommended alternative is to use the Membership APIs, such as Membership.CreateUser. For more information, see http://go.microsoft.com/fwlink/?LinkId=252463.”
            writer.WriteValue(pwd);
            writer.WriteEndObject();
            writer.Flush();
            string json = sw.GetStringBuilder().ToString();
            var js = new JavaScriptSerializer();
            var dic = js.Deserialize<Dictionary<string, object>>(gt.postReturnJson(url, json));
            //Dictionary<string, object> dic = GetReturnJson.CreatePostHttpResponse(url, json, null, null, Encoding.GetEncoding("utf-8"),null);
            

            if (dic["errcode"].ToString().Equals("0"))
            {
                // 同步更新数据库
                kf.alterKefu(kefuName, password, kefuAccount);
                ApplicationLog.Write("修改客服成功！");
                return "修改客服成功！kefuAccount:" + kefuAccount;

            }
            else
            {
                ApplicationLog.Write("修改客服失败！errcode：" + dic["errcode"]);
                return "修改客服失败！errcode：" + dic["errcode"];
            }
        }
        /// <summary>
        /// 删除客服
        /// </summary>
        /// <param name="kefuAccount">客服账号</param>
        public string delKefu(string kefuAccount)
        {
            string url = "https://api.weixin.qq.com/customservice/kfaccount/del?access_token=" + GetAccess_token.getAccesstoken() + "&kf_account=" + kefuAccount;

            var js = new JavaScriptSerializer();
            var dic = js.Deserialize<Dictionary<string, object>>(gt.getReturnJson(url));
            //Dictionary<string, object> dic = GetReturnJson.CreatePostHttpResponse(url, json, null, null, Encoding.GetEncoding("utf-8"),null);


            if (dic["errcode"].ToString().Equals("0"))
            {
                //同步更新数据库 
                if (kf.delKefu(kefuAccount))
                {
                    ApplicationLog.Write("删除客服成功！");
                    return "删除客服成功!kefuAccount:" + kefuAccount;
                }
                else
                {
                    return "删除客服成功，同步至数据库失败！";
                }
            }
            else
            {
                ApplicationLog.Write("删除客服失败！errcode：" + dic["errcode"]);
                return "删除客服失败！errcode：" + dic["errcode"];
            }
        }
        /// <summary>
        /// 获取所有客服信息,并同步到数据库
        /// </summary>
        /// <param name="password">设置初始化密码</param>
        public int getKefu(string password)
        {
            string url = "https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token=" + GetAccess_token.getAccesstoken();
            string json = gt.getReturnJson(url);

            DataTable dt = setDatatable();

            JObject jo = JObject.Parse(json);
            JArray ja = JArray.Parse(jo["kf_list"].ToString());
            foreach (JToken jt in ja)
            {
                string kf_account = jt["kf_account"].ToString();//完整客服账号，格式为：账号前缀@公众号微信号
                string kf_headimgurl = jt["kf_headimgurl"].ToString();//客服头像地址
                //string kf_id = jt["kf_id"].ToString();//客服工号
                string kf_nick = jt["kf_nick"].ToString();//客服昵称
                /*
                 *清空，再批量插入
                 *获取客服信息在页面后台写调取数据库数据
                 */
                kf.truncKefu();
                dt.Rows.Add(new object[] { null, kf_account, kf_nick, password });
            }
            int i = kf.updateKefu(dt);
            return i;
        }

        /// <summary>
        /// 获取在线状态客服
        /// </summary>
        /// <returns></returns>
        public DataTable getKefuStates()
        {
            string url = "https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist?access_token=" + GetAccess_token.getAccesstoken();
            //string jsons = gt.getReturnJson(url);
            string jsons = HttpService.Get(url);
            if (!jsons.Contains("errcode"))
            {
                DataTable dt = kfOnline();
                JObject jo = JObject.Parse(jsons);
                JArray ja = (JArray)JsonConvert.DeserializeObject(jo["kf_online_list"].ToString());
                foreach (JToken jt in ja)
                {
                    string kf_account = jt["kf_account"].ToString();//客服账号
                    string status = jt["status"].ToString();//在线状态
                    switch (status)
                    {
                        case "1":
                            status = "pc在线";
                            break;
                        case "2":
                            status = "手机在线";
                            break;
                        case "3":
                            status = "两端在线";
                            break;
                    }
                    int accepted_case = Int32.Parse(jt["accepted_case"].ToString());//正在接待数量
                    dt.Rows.Add(new object[] { null, kf_account, status, accepted_case });
                }
                return dt;
            }
            else
            {
                ApplicationLog.Write("获取在线状态客服报错：" + jsons);
                DataTable dt = kfOnline();
                return dt;
            }
        }

        //新建一个表结构和kefu一样的datatable，并插入数据批量保存
        private DataTable setDatatable()
        {
            DataTable dt = new DataTable();
            DataColumn dc = dt.Columns.Add("id", Type.GetType("System.Int32"));
            dc.AutoIncrement = true;//自动增加
            dc.AutoIncrementSeed = 1;//起始为1
            dc.AutoIncrementStep = 1;//步长为1
            dc.AllowDBNull = false;

            dt.Columns.Add("kf_account", Type.GetType("System.String"));
            dt.Columns.Add("kf_nick", Type.GetType("System.String"));
            //dt.Columns.Add("kf_id", Type.GetType("System.Int32"));
            dt.Columns.Add("password", Type.GetType("System.String"));
            return dt;
        }

        //客服在线接待信息
        private DataTable kfOnline()
        {
            DataTable dt = new DataTable();
            DataColumn dc = dt.Columns.Add("id", Type.GetType("System.Int32"));
            dc.AutoIncrement = true;//自动增加
            dc.AutoIncrementSeed = 1;//起始为1
            dc.AutoIncrementStep = 1;//步长为1
            dc.AllowDBNull = false;

            dt.Columns.Add("kf_account", Type.GetType("System.String"));//客服账号
            dt.Columns.Add("status", Type.GetType("System.String"));//在线状态
            dt.Columns.Add("accepted_case", Type.GetType("System.Int32"));//正在接待数量
            return dt;
        }
    }
}
